package b.olap

import com.softwaremill.quicklens._

final case class Cube(
                       name: String,
                       cols: Map[String, FactColumn] = Map.empty[String, FactColumn],
                       dims: Map[String, Dim] = Map.empty[String, Dim],
                       whereSegment: Option[String] = None
                     ) {
  def addDimDef(dim: String, value: String, label: String) =
    this.modify(_.dims.at(dim).defs).using(_.::(DimDef(label, value)))

  def addCol(name: String, label: String, `type`: String, width: Int, input: String) = {
    val col = FactColumn(name, label, FactType.withName(`type`), width, input)
    this.modify(_.cols.at(name)).setTo(col)
  }

  val sqlSegment: String = {
    val facts = cols.values.toList.filter(_.`type` == FactType.Fact)
    val sums = facts.map(f => s"SUM(${f.name}) ${f.name}_sum").mkString(", ")
    s"$sums, COUNT(*) c_count FROM t_ec_fact_$name"
  }

  def getDimDef(dim: String, value: String): String = {
    dims.get(dim).flatMap(_.defs.find(_.value == value)).map(_.label).orNull
  }

  def getDigDims(dimsX: List[String]) = {
    val dims = cols.values.toList.filter(_.`type` == FactType.Dim).map(_.name)
    dims.diff(dimsX)
  }

  def getColLabel(name: String) =
    cols.get(name).map(_.label).orNull
}
